package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     用户登录
     api/user/passport/login
     接口路径：POST/api/user/passport/login
    */
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){

        //认证用户
        UserInfo user = userService.login(userInfo);

        //判断
        if (user != null) {
            //生成token
            String token = UUID.randomUUID().toString().replaceAll("-","");

            //1、封装页面需要的数据
            HashMap<String, Object> resultMap = new HashMap<>();
            //token
            resultMap.put("token", token);
            //nickName
            resultMap.put("nickName",user.getNickName());


            //2、封装redis中需要认证的数据 --字符串 key ---token     userId  Ip
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId",user.getId());
            jsonObject.put("ip", IpUtil.getIpAddress(request));


            //key -token     value   userId   ip
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,jsonObject.toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);


            return Result.ok(resultMap);

        }else {

            return Result.fail().message("用户名或者密码错误！！");
        }


    }


    /**
     用户退出
     api/user/passport/logout
    */
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){

        String key=RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token");
        redisTemplate.delete(key);

        return Result.ok();
    }



}
